#pragma once

#include <string>
#include <iostream>
#include <map>

using namespace std;

#include "topdbs_connection.hpp"

namespace topdbs
{
	struct STRwConn
	{
		SQLConnection* m_pConnection;
		eConnSt_t m_status;
		eRwType_t m_rwtype;
		virtual ~STRwConn()
		{
			if(m_pConnection)
			{
				delete m_pConnection;
				m_pConnection = nullptr;
			}
		}
	};
	
	class TOPDBS_API SQLConnectionRw 
	{
		private:
			std::map<uint64_t,STRwConn*> m_StConns;
            
			static std::mutex  m_lock; 
			static SQLConnectionRw* m_instance;
			static bool m_status;
            static uint16_t m_current_pos;
			class AutoRelease
			{
				public:
				~AutoRelease()
				{
					UnInitEnv();
				};
			};	    
			static AutoRelease m_release; 
					
			SQLConnectionRw()=default;
		public:
			virtual ~SQLConnectionRw();
				
			int NewConnectionRW( 
				eDBSClient_t dbsClient,
				const string& dbString,
				const string& user ,
				const string& pass ,
				const string& charset, 
				bool encrypt,
				eRwType_t rwType );
			int DeleteSQLConnectionRw();
			SQLConnection* GetIdleConnection(const string& sSQL,bool isForce);
			int ReleaseIdleConnection(SQLConnection* pConnection);
				
		public:
			static SQLConnectionRw* getInstance();
			static int InitEnv( const string& dbsfile,const string& dbs_master_name,const string& dbs_slave_name);
            static int InitEnv( std::vector<DBSConnectionParams>& master_dbsParams,std::vector<DBSConnectionParams>& slave_dbsParams);
			static SQLConnection* GetConnection(const string& sSQL,bool isForce = false);
			static int ReleaseConnection(SQLConnection* pConnection);
			static int UnInitEnv();	
	};
	
}